package tenantchannellogic

import (
	"context"

	model "gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/dao/model/tenant/channel"
	"gitee.com/liuxuezhan/ar-platform/assets-rpc/pkg/xerrors"

	"gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/assets-rpc/rpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type BankUpdateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBankUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BankUpdateLogic {
	return &BankUpdateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *BankUpdateLogic) BankUpdate(in *rpc.BankUpdateRequest) (*rpc.BankUpdateResponse, error) {
	var CommonResp rpc.CommonResp

	bankModel := model.NewTenantChannelBankModel(l.ctx, l.svcCtx.Db)
	bank, err := bankModel.GetBankById(in.Id)
	if err != nil {
		CommonResp.Code = xerrors.DBError
		CommonResp.Message = "Bank not found"
		return &rpc.BankUpdateResponse{
			CommonResp: &CommonResp,
		}, err
	}

	// Update fields if they are not empty or zero
	if in.Code != "" {
		bank.Code = in.Code
	}
	if in.Phone != "" {
		bank.Phone = in.Phone
	}
	if in.MinAmount != 0 {
		bank.MinAmount = in.MinAmount
	}
	if in.MaxAmount != 0 {
		bank.MaxAmount = in.MaxAmount
	}
	if in.DailyTimes != 0 {
		bank.DailyTimes = in.DailyTimes
	}
	if in.DailyAmount != 0 {
		bank.DailyAmount = in.DailyAmount
	}
	if in.RemainTimes != 0 {
		bank.RemainTimes = in.RemainTimes
	}
	if in.RemainAmount != 0 {
		bank.RemainAmount = in.RemainAmount
	}
	if in.VisionLevel != "" {
		bank.VisionLevel = in.VisionLevel
	}
	if in.IsDisplay != 0 {
		bank.IsDisplay = in.IsDisplay
	}
	if in.CardNumber != "" {
		bank.CardNumber = in.CardNumber
	}
	if in.BankNickname != "" {
		bank.BankNickname = in.BankNickname
	}
	if in.BankName != "" {
		bank.BankName = in.BankName
	}
	if in.IfscCode != "" {
		bank.IfscCode = in.IfscCode
	}
	if in.Email != "" {
		bank.Email = in.Email
	}
	if in.Province != "" {
		bank.Province = in.Province
	}
	if in.City != "" {
		bank.City = in.City
	}
	if in.BranchBank != "" {
		bank.BranchBank = in.BranchBank
	}
	if in.IsLimit > 0 {
		bank.IsLimit = in.IsLimit
	}
	if in.CardHolder != "" {
		bank.CardHolder = in.CardHolder
	}
	if in.Sort > 0 {
		bank.Sort = in.Sort
	}

	err = bankModel.UpdateBank(bank)
	if err != nil {
		CommonResp.Code = xerrors.DBError
		CommonResp.Message = "Database operation error"
		return &rpc.BankUpdateResponse{
			CommonResp: &CommonResp,
		}, err
	}

	CommonResp.Message = "Success"
	return &rpc.BankUpdateResponse{
		CommonResp: &CommonResp,
	}, nil
}
